﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace csharpcore7_ch14_ConcurrencyAndAsynchrony
{
    class Chapt14_4_4AsynchronousProgrammingAndContinuation
    {
       static int GetPrimesCount(int start, int count)
        {
            return
                ParallelEnumerable.Range(start, count).Count(n =>
                    Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i => n % i > 0));
        }
        static void DisplayPrimeCounts()
        {
            for (int i = 0; i < 10; i++)
                Console.WriteLine(GetPrimesCount(i * 1000000 + 2, 1000000) +
                    " primes betwwen " + (i * 1000000) + " and " + ((i+1)*1000000 - 1));
        }

        static Task<int> GetPrimesCountAsync(int start, int count)
        {
            return Task.Run(()=>
             ParallelEnumerable.Range(start, count).Count(n =>
                    Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i => n % i > 0)));
        }

        static async Task DisplayPrimeContsAsync()
        {
            for (int i = 0; i < 10; i++)
                Console.WriteLine(await GetPrimesCountAsync(i * 1000000 + 2, 1000000) +
                    " primes betwwen " + (i * 1000000) + " and " + ((i + 1) * 1000000 - 1));
            Console.WriteLine("Done");
        }
    

        static void Main()
        {
            //DisplayPrimeCounts();

            // Task.Run(() => DisplayPrimeCounts());

            //DisplayPrimeContsAsync().GetAwaiter().GetResult();

            async void DisplayPrimesCount()
            {
                int result = await GetPrimesCountAsync(2, 1000000);
                Console.WriteLine(result);
            }

            DisplayPrimesCount();


            Console.Read();
        }
    }
}
